<template>
  <div class="table-mechanism">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-button icon="el-icon-plus" type="primary"  @click="EditADD">
          添加用户
        </el-button>


      </vab-query-form-left-panel>
      <vab-query-form-right-panel>

        <el-form
          ref="form"
          size="mini"
          :inline="true"
          @submit.native.prevent
        >
          <el-form-item>
            <el-input v-model="organ.uname" placeholder="账户名" />
          </el-form-item>
          <el-select v-model="organ.institutionNumber" placeholder="请选择"     size="mini" style="margin-top: 6px">
            <el-option
              v-for="item in options"
              :key="item.institutionNumber"
              :label="item.institutionName"
              :value="item.institutionNumber">
            </el-option>
          </el-select>
          <el-form-item>

            <el-button

              icon="el-icon-search"
              type="primary"
              native-type="button"
              @click="find()"
            >
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-container style="height: 500px; border: 1px solid #eee">
<!--      <el-aside width="200px" style="background-color: rgb(238, 241, 246)">-->
<!--        <el-menu :default-openeds="['1', '3']" @close="handleClose">-->
<!--          <el-submenu index="1">-->
<!--            <template slot="title"><i class="el-icon-user"></i>全部角色</template>-->
<!--            <el-menu-item-group >-->

<!--                    <el-menu-item  ref="uname" @click.native="search($event)" :index="(index+'')"-->
<!--                                   :data-index="item.roleCode"  :data-in="item.institutionNumber" v-for="(item,index) in roles" :key="index">{{item.roleName}}</el-menu-item>-->



<!--            </el-menu-item-group>-->



<!--          </el-submenu>-->


<!--        </el-menu>-->
<!--      </el-aside>-->

      <el-container>
        <el-main>
          <el-table
            ref="tableSort"
            v-loading="listLoading"
            :data="list"
          >
            <el-table-column show-overflow-tooltip label="账户名" width="200"  prop="uname">

            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="institutionName"
              label="机构名称"

            ></el-table-column>

            <el-table-column
              show-overflow-tooltip
              label="用户名"
              prop="userName"
            ></el-table-column>
            <el-table-column label="禁用状态" prop="gender">
              <template slot-scope="scope">
                <span v-if="scope.row.disabled==true">

             <el-tag type="warning">禁用</el-tag>
                </span>
                <span v-if="scope.row.disabled==false">     <el-tag type="success">启用</el-tag></span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="备注信息"
              prop="remark">
            </el-table-column>

            <el-table-column
              show-overflow-tooltip
              label="创建者"
              prop="creatorName"
            ></el-table-column>

            <el-table-column
              show-overflow-tooltip
              label="操作"
              width="280px"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button type="text"  @click="handleEdit(scope.$index, scope.row)" >编辑</el-button>
<!--                <el-button type="text"  @click="handleDelete(scope.$index, scope.row)">-->
<!--                  删除-->
<!--                </el-button>-->
                                <el-button type="text"  @click="disable(scope.$index, scope.row)" v-if="!scope.row.disabled">
                                  禁用
                                </el-button>
                <el-button type="text"  @click="enable(scope.$index, scope.row)" v-if="scope.row.disabled">
                  启用
                </el-button>
                <el-button type="text" @click="handleInfo(scope.$index, scope.row)" >
                  查看详情
                </el-button>
                <el-button type="text" @click="handledis(scope.$index, scope.row)" >
                  分配角色
                </el-button>
                <el-button type="text"  @click="handlePass(scope.$index, scope.row)">
                  重置密码
                </el-button>

              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :background="background"


            :total="total"
            :page-size="queryForm.limit"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          ></el-pagination>
        </el-main>
      </el-container>
    </el-container>

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="500px"

    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="机构编号" prop="institutionNumber" >

          <el-select
            style="width: 100%"
            v-model="form.institutionNumber"
            width="400px"
            placeholder="机构名称">
            <el-option

              v-for="item in organss"
              :key="item.institutionNumber"
              :label="item.institutionName"
              :value="item.institutionNumber">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="账号" prop="uname">
          <el-input v-model.trim="form.uname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model.trim="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="userName">
          <el-input v-model.trim="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model.trim="form.phoneNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="助记码" prop="shorthandCode">
          <el-input v-model.trim="form.shorthandCode" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="备注信息" prop="remark">
          <el-input v-model.trim="form.remark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-radio v-model="form.userType" label='1' @change="changeuser">普通用户</el-radio>
          <el-radio v-model="form.userType" label='0' @change="changeuser">管理员</el-radio>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="SaveAdd">确 定</el-button>
      </div>

    </el-dialog>





    <el-dialog
      title="修改用户信息"
      :visible.sync="dialogFormVisibles"
      width="500px"

    >
      <el-form ref="form" :model="secondlist" :rules="rule" label-width="80px">

        <el-form-item label="机构编号" prop="institutionNumber">
          <el-input v-model.trim="secondlist.institutionNumber" autocomplete="off" disabled></el-input>
        </el-form-item>

        <el-form-item label="机构名称" prop="institutionNumber">
          <el-input v-model.trim="secondlist.institutionName" autocomplete="off" disabled></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model.trim="secondlist.phoneNumber" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="助记码" prop="shorthandCode">
          <el-input v-model.trim="secondlist.shorthandCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="uname">
          <el-input v-model.trim="secondlist.uname" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="userName">
          <el-input v-model.trim="secondlist.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model.trim="secondlist.remark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="禁用状态">

<!--            <el-switch-->
<!--              v-model="secondlist.disabled"-->
<!--              active-text="启用"-->
<!--              inactive-text="禁用"-->
<!--              @change="changebutton"-->
<!--            >-->
<!--            </el-switch>-->

            <el-switch
              v-model="secondlist.disabled"
              class="demo"
              active-color="#F04134"
              active-text="禁用"
              font-size="12px"
              inactive-color="#11CED2"
              inactive-text="启用"
              @change="switchChange"

            />


        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="secondlist.userType">
            <el-radio label="1">普通用户</el-radio>
            <el-radio label="0">管理员</el-radio>

          </el-radio-group>

        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="handleEditor" >确 定</el-button>
      </div>

    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="dialogFormVisibless"
      width="500px"

    >





      <el-checkbox-group v-loading="roleByUnameLoading" v-model="checkedCities" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="city in cities" :label="city.roleCode" :key="city.roleName"  >{{city.roleName}}</el-checkbox>
      </el-checkbox-group>




      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary"  @click="distribute" >确 定</el-button>
      </div>

    </el-dialog>
    <password ref="pas"></password>
    <perInforEdit ref="perinfo"></perInforEdit>
  </div>

</template>

<script>
    import { Editor } from "../../../api/personnel";
    import { doDelete,disable,enable } from "../../../api/personnel";
    import { searchrole ,searchUserRoleByUname} from "../../../api/personnel";
    import { doEdit } from "@/api/personnel";
    import { role } from "@/api/personnel";
    import { distribute } from "@/api/personnel";
    import { searchList} from "../../../api/personnel";
    import password from "./components/password";
    import { search} from "../../../api/personnel";
    import perInforEdit from "./components/perInforEdit";

    export default {
        name: "Personnel",
        components: {password,perInforEdit},
        data() {
            return {
              checkAll: false,
              checkedCities: [],
              organs:"",
                checked:{

                },
              organss:[],
              cities: {

              },
              roleByUnameLoading: false,
              isIndeterminate: true,
                title: "添加用户",
                dialogFormVisible: false,
                dialogFormVisibles: false,
              dialogFormVisibless: false,
                background: true,
                listLoading: true,
                list: [],
                roles: [],

                total: 0,
                secondlist: {},

                organ: {
                    uname: "",
                    institutionNumber:"",
                    currPageNo: 1,
                    limit: 8,
                },
                value:"",
                options:[],

                layout: "total, sizes, prev, pager, next, jumper",
                form: {
                    creator: "",
                    institutionNumber: "",
                    password: "",
                    phoneNumber: "",
                    remark: "",
                    shorthandCode: "",
                    uname: "",
                    userName: "",
                    userType: '1',


                },
                rule: {
                    creator: [{required: true, trigger: "blur", message: "创建者"}],
                    institutionNumber: [{required: true, trigger: "blur", message: "请输入机构编号"}],
                    remark: [{trigger: "blur", message: "备注信息"}],
                    phoneNumber: [{required: true, trigger: "blur", message: "手机号"}],
                    password: [{required: true, trigger: "blur", message: "用户密码"}],
                    shorthandCode: [{trigger: "blur", message: "助记码"}],
                    uname: [{required: true, trigger: "blur", message: "账号"}],
                    userName: [{required: true, trigger: "blur", message: "名称"}],
                    userType: [{trigger: "blur", message: "用户类型"}],
                },
                rules: {
                    creator: [{required: true, trigger: "blur", message: "创建者"}],
                    institutionNumber: [{required: true, trigger: "blur", message: "请输入机构编号"}],
                    remark: [{trigger: "blur", message: "备注信息"}],
                    phoneNumber: [{required: true, trigger: "blur", message: "手机号"}],
                    password: [{required: true, trigger: "blur", message: "用户密码"}],
                    shorthandCode: [{trigger: "blur", message: "助记码"}],
                    uname: [{required: true, trigger: "blur", message: "账号"}],
                    userName: [{required: true, trigger: "blur", message: "名称"}],
                    userType: [{trigger: "blur", message: "用户类型", type: 'number'}],
                },
                queryForm: {
                    currPageNo: 1,
                    limit: 8,
                    institutionNumber: "",
                    name: "",

                },
                roled: {
                    roleCodes: [

                    ],
                    uname:"",

              }
            };
        },

        created(){
          setTimeout(() => {
              this.options = JSON.parse(localStorage.getItem("childinstitutionNumber"));
            this.organss = JSON.parse(localStorage.getItem("childinstitutionNumber"));
            // this.form.institutionNumber=localStorage.getItem("institutionNumber")
            this.organ.institutionNumber=localStorage.getItem("institutionNumber")
            this.find()
            this.role()
          }, 1000);



        },
        methods:{
          handleCheckAllChange(val) {
            this.checkedCities = val ? this.cities : [];
            this.isIndeterminate = false;
            console.log(val)
          },
          handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.cities.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
            console.log(value)

            this.roled.roleCodes=value
          },

            EditADD(row) {
                this.form.institutionNumber=localStorage.getItem("institutionNumber")
                this.dialogFormVisible = true;
            },
            handledis(id,row){
              this.roleByUnameLoading = true
              this.checkedCities = []
                let institutionNumber=row.institutionNumber
                let  uname=row.uname
                role({institutionNumber}).then(res =>{

                    this.roles=res.data.data
                    this.cities=res.data.data
                    console.log(res.data.data)

                })
                searchUserRoleByUname({uname }).then(result =>{
                  this.roleByUnameLoading = false
                  let checked = []
                  if(result.data){
                    result.data.forEach(item => {
                      checked.push(item.roleCode)
                    })
                  }
                  this.checkedCities = checked
                    // res.data.map((item) => {
                    //         console.log(item)
                    //     const idx =this.cities.findIndex(sla => sla[this.roleCode] === item[this.roleCode])

                    //     this.cities[idx] = item

                    // })

                })




              this.roled.uname=row.uname
              this.dialogFormVisibless = true;

            },
            distribute(){
               console.log(this.roled)
                distribute(this.roled).then(res =>{
                    console.log(res)
                  if(res.code==200){
                    this.$message({
                      message: "分配成功",
                      type: 'success'
                    })
                    this.close()
                  }

                })
            },
            disable(id,row){
              let uname=row.uname
                disable({uname}).then(res =>{
                    console.log(res)
                    if(res.code==200){
                        this.$message({
                            message: "已禁用",
                            type: 'success'
                        })
                        this.find()
                    }

                })
            },
            enable(id,row){
                let uname=row.uname
                enable({uname}).then(res =>{
                    console.log(res)
                    if(res.code==200){
                        this.$message({
                            message: "已启用",
                            type: 'success'
                        })
                        this.find()
                    }

                })
            },
            handleEdit(index, row) {
                //console.log(row);

                this.dialogFormVisibles = true;
                this.secondlist={
                    ...row,
                  userType:row.userType +'',
                  disableds:row.disabled,

                }
                console.log( this.secondlist)


            },
            switchChange(value){
               console.log(value)
            this.secondlist.disableds =value
          },
          //   searchList(){
          //     this.listLoading = true;
          //     search( this.organ).then(res =>{
          //         console.log(res)
          //       this.list=res.data.data
          //         this.total=res.data.total
          //
          //     })
          //     setTimeout(() => {
          //         this.listLoading = false;
          //     }, 500)
          // } ,


          search(ev){

                console.log(ev.target.dataset.index)
              this.queryForm.name = ev.target.dataset.index
              this.queryForm.institutionNumber = ev.target.dataset.in

               searchrole(this.queryForm).then(res =>{
                 console.log(res.code)

            })












            },
            handleInfo(index,row) {

                this.$refs["perinfo"].showEdit(row);
            },
            changeuser(lable){
             this.form.userType=lable
            },
            close() {
              this.dialogFormVisibless=false,
                this.dialogFormVisibles=false,
                this.dialogFormVisible = false;

            },
            handleQuery() {

                this.fetchData();
            },
            handlePass(index,row) {

                this.$refs["pas"].showEdit(row);
            },
            async fetchData() {

                this.listLoading = true;
                this.list=[];
                this.total=0;
                const result = await searchList(this.organ);
                console.log(result.data)

                if(result.data==undefined){

                }else {
                    this.list.push(result.data)
                }






                setTimeout(() => {
                    this.listLoading = false;
                }, 500);
            },
          handleClose(){
              // this.find()
          },
            role(){


            },

            async find() {
                this.listLoading = true;

                const { data, total } = await search(this.organ);
                this.list=data.data
                this.total=data.total
                console.log(data.data)


                setTimeout(() => {
                    this.listLoading = false;
                }, 500);
            },
            SaveAdd() {
                doEdit(this.form).then(res =>{
                    if(res.code==200){
                        this.$baseMessage("添加成功");
                        this.close()
                        this.find();
                    }else {
                        return false;
                    }


                    }





                ).catch(err => console.log(err))
            },
            handleDelete(index,row) {
              let uname =(row.uname)

              if (row.id) {
                    this.$baseConfirm("你确定要删除当前项吗", null, async () => {
                        const { msg } = await doDelete(({uname}));
                        this.$baseMessage(msg, "success");
                        this.find();
                    });
                }
            },
            handleSizeChange(val) {
                this.queryForm.limit = val;
                this.find();
            },
            handleCurrentChange(val) {
                this.queryForm.currPageNo = val;
                this.find();
            },
            async add() {

              const {code} = await Editor({...this.secondlist,
                 disabled:this.secondlist.disableds+''


               });
                if(code==200){

                    this.$baseMessage("编辑成功");
                    this.close()
                    this.find();
                }else {
                    return  false
                }




            },
            handleEditor(){

            this.add()

            }
        }
    }
</script>

<style scoped>
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }
  .table-mechanism >>> .demo .el-switch__label {
    position: absolute !important;
    display: none !important;
    color: #fff !important;
  }
  .table-mechanism >>>.el-switch__core{
    width: 50px !important;
  }
  /*打开时文字位置设置*/
  .table-mechanism >>> .demo .el-switch__label--right {
    z-index: 1 !important;

  }
  /*关闭时文字位置设置*/
  .table-mechanism >>> .demo .el-switch__label--left {
    z-index: 1 !important;
    left: 19px !important;
    margin-right: 0px !important;
  }
  /*显示文字*/
  .table-mechanism >>> .demo .el-switch__label.is-active {
    display: block !important;

  }
  .table-mechanism >>> .demo .el-switch__label.is-active span{
    font-size: 12px !important;
  }
  .table-mechanism >>> .demo.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 50px !important !important;
  }
</style>
